package be.ipl.streams.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.ipl.streams.domaine.Game;
import be.ipl.streams.domaine.Player;
import be.ipl.streams.usecases.GameManagement;

@WebServlet("/log.html")
public class GameLog extends HttpServlet implements Servlet {
	private static final long serialVersionUID = 1L;
	
	@EJB
	private GameManagement gameManagement;
	
	@Override
	protected void doPost (HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		Player player = (Player) Controleur.testConnected(this, request, response);
		if (player == null) return;
		
		int idGame = Integer.parseInt(request.getParameter("gameID"));
		String log = gameManagement.checkGameLog(idGame);
		request.setAttribute("log"+idGame, log);
		RequestDispatcher rd = getServletContext().getNamedDispatcher("log");
		rd.forward(request, response);
	}
	
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		Player player = (Player) Controleur.testConnected(this, request, response);
		if (player == null) return;
		
		List<Game> allGames = gameManagement.listAllGames();
		List<Game> gamesToLog = new ArrayList<Game>();
		
		for (Game game : allGames) {
			if (game.getState() == Game.GameState.PLAYING 
					|| game.getState() == Game.GameState.ENDED)
				gamesToLog.add(game);
		}
		
		request.setAttribute("games", gamesToLog);
		RequestDispatcher rd = getServletContext().getNamedDispatcher("parties");
		rd.forward(request, response);
	}
}
